package com.saifan.wyy_ov.ui.onlishop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.BaseActivity;
import com.saifan.wyy_ov.common.IconText;
import com.saifan.wyy_ov.data.bean.GroupBuyBean;
import com.saifan.wyy_ov.data.bean.GroupBuyBean.GoodsList;
import com.saifan.wyy_ov.data.bean.GroupBuyGoodDetailBean;
import com.saifan.wyy_ov.data.bean.PopBean;
import com.saifan.wyy_ov.config.Api;

import com.saifan.wyy_ov.ui.zoomimage.ZoomImageActivity;
import com.saifan.wyy_ov.utils.CallPhoneUtil;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.PriceUtils;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import cn.lightsky.infiniteindicator.InfiniteIndicatorLayout;
import cn.lightsky.infiniteindicator.slideview.BaseSliderView;
import cn.lightsky.infiniteindicator.slideview.DefaultSliderView;
import cn.lightsky.infiniteindicator.slideview.TextSliderView;
import lomasky.ma.utils.DensityUtil;

public class GroupBuyDetailsActivity extends BaseActivity implements BaseSliderView.OnSliderClickListener {
    private Toolbar toolbar;
    private TextView tv_group_buy_price;
    private TextView tv_price;
    private TextView bt_go_buy;
    private ImageView iv_IsDelivery;
    private TextView tv_IsDelivery;
    private TextView tv_DeliveryInstructions;
    private TextView tv_sold;
    private TextView tv_GroupBuyingRemainingCount;
    private TextView tv_goods_count;
    private TextView groupbuy_time;
    private TextView tv_GoodsInstruction;
    private TextView tv_store;
    private TextView tv_address;
    private TextView tv_business_hours;
    private Button tv_tel;
    private TextView tv_store_comments;
    private com.saifan.wyy_ov.ui.view.NoScrollListView listView;
    private InfiniteIndicatorLayout slider;
    private static final int GROUPBUY = 5555;
    private GoodsList goodsList;
    private GroupBuyBean groupBuyBean;
    private String jsonString;
    private List<GroupBuyGoodDetailBean> groupBuyDetailBeans = new ArrayList<GroupBuyGoodDetailBean>();
    private CommonAdapter<com.saifan.wyy_ov.data.bean.GoodsList> adapter;
    private ArrayList<PopBean> popList;
    protected GroupBuyGoodDetailBean groupBuyGoodDetailBean;
    private ArrayList<String> urls = new ArrayList<String>();
    private HashMap<String, String> url_maps = new HashMap<String, String>();
    private ListPopupWindow listPopupWindow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        goodsList = (GoodsList) extras.get("goods");
        groupBuyBean = (GroupBuyBean) extras.get("groupBuyBean");
        jsonString = getIntent().getStringExtra("json");
        setContentView();
        groupBuyDetailBeans = new Gson().fromJson(jsonString, new TypeToken<List<GroupBuyGoodDetailBean>>() {
        }.getType());
        if (groupBuyDetailBeans != null && groupBuyDetailBeans.size() > 0) {
            groupBuyGoodDetailBean = groupBuyDetailBeans.get(0);
            initSlider();
        }

        initPopList();
        if (!groupBuyGoodDetailBean.equals(null)) {
            initView();
        }

        setEnabledNavigation(true);

    }

    private void initPopList() {
        listPopupWindow = new ListPopupWindow(this);
        lomasky.ma.xui.CommonAdapter adapter = new lomasky.ma.xui.CommonAdapter<IconText>(this, R.layout.pop_item) {
            @Override
            public void onBind(lomasky.ma.xui.ViewHolderHelper holder, IconText iconText, int i) {
                holder.setImage(R.id.pop_img, iconText.icon);
                holder.setText(R.id.pop_text, iconText.text);
            }
        };
        List<IconText> list = new ArrayList<>();
        list.add(new IconText(R.mipmap.home_default, "商城首页"));
        list.add(new IconText(R.mipmap.cart_insidepage, "我的购物车"));
        list.add(new IconText(R.mipmap.order_all, "我的订单"));
        list.add(new IconText(R.mipmap.collect_abolish, "我的收藏"));

        adapter.setData(list);

        listPopupWindow.setAdapter(adapter);
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent();
                switch (position) {
                    case 0:
                        intent.setClass(GroupBuyDetailsActivity.this, OnlineShopActivity.class);
                        break;
                    case 1:
                        intent.setClass(GroupBuyDetailsActivity.this, MyCartActivity.class);
                        break;
                    case 2:
                        intent.setClass(GroupBuyDetailsActivity.this, MyOrderActivity.class);
                        break;
                    case 3:
                        //
                        intent.setClass(GroupBuyDetailsActivity.this, MyCollectActivity.class);
                        break;
                }
                GroupBuyDetailsActivity.this.startActivity(intent);
                listPopupWindow.dismiss();



            }
        });

    }

    private void initView() {

        final List<com.saifan.wyy_ov.data.bean.GoodsList> goodsLists;
        goodsLists = groupBuyGoodDetailBean.getGoodsList();

        if (goodsLists != null && !goodsLists.isEmpty()) {
            adapter = new CommonAdapter<com.saifan.wyy_ov.data.bean.GoodsList>(GroupBuyDetailsActivity.this, goodsLists, R.layout.goods_item) {
                @Override
                public void convert(ViewHolderHelper helper, com.saifan.wyy_ov.data.bean.GoodsList item) {
                    helper.setText(R.id.goods_name, StringUtil.returnShow(item.getGoodsName()));
                    helper.setText(R.id.goods_category, StringUtil.returnShow(item.getGoodsType()));
                    helper.setText(R.id.goods_price, "店铺价: " + PriceUtils.getPrice(item.getGoodsPrice()) + "元");
                    helper.setText(R.id.sales, "已售: " + StringUtil.returnShow(item.getSold()));
                    helper.setImageByUrl(R.id.goods_img, item.getCoverPhoto());
                }
            };
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    Intent intent = new Intent(GroupBuyDetailsActivity.this, GoodsDetailActivity.class);
                    intent.putExtra("storeId", String.valueOf(groupBuyBean.getID()));
                    intent.putExtra("goodsId", goodsLists.get(arg2).getID());
                    intent.putExtra("goodsName", goodsLists.get(arg2).getGoodsName());
                    intent.putExtra("price", goodsLists.get(arg2).getGoodsPrice());
                    startActivity(intent);
                }
            });
            listView.setFocusable(false);
        }
        tv_address.setText(StringUtil.returnShow(groupBuyGoodDetailBean.getAddress()));

        tv_business_hours.setText("营业时间:" + StringUtil.returnShow(groupBuyGoodDetailBean.getBusinessDate()).replace(",", "至") + " " + StringUtil.returnShow(groupBuyGoodDetailBean.getBusinessTime()).replace(",", "至"));
        tv_tel.setText("联系商家：" + groupBuyGoodDetailBean.getTel());
        tv_store.setText(StringUtil.returnShow(groupBuyGoodDetailBean.getStoreName()));
        tv_GoodsInstruction.setText(StringUtil.returnShow(groupBuyGoodDetailBean.getGoodsInstruction()));
        tv_DeliveryInstructions.setText(StringUtil.returnShow(groupBuyGoodDetailBean.getDeliveryAmount()) + "起送 ！" + StringUtil.returnShow(groupBuyGoodDetailBean.getDeliveryInstructions()));
        if (!groupBuyGoodDetailBean.isIsDelivery()) {
            iv_IsDelivery.setVisibility(View.INVISIBLE);
            tv_IsDelivery.setText("不支持送货");
            tv_DeliveryInstructions.setVisibility(View.INVISIBLE);
        }

        String startTime = "";
        if (goodsList.getGroupBuyingStartTime() != null && goodsList.getGroupBuyingStartTime().length() > 17) {
            startTime = goodsList.getGroupBuyingStartTime().substring(0, 10) + " " + goodsList.getGroupBuyingStartTime().substring(11, 16);

        }
        String endTime = "";
        if (goodsList.getGroupBuyingEndTime() != null && goodsList.getGroupBuyingEndTime().length() > 17) {
            endTime = goodsList.getGroupBuyingEndTime().substring(0, 10) + " " + goodsList.getGroupBuyingEndTime().substring(11, 16);
        }
        groupbuy_time.setText(startTime + " 至 " + endTime);

        tv_group_buy_price.setText(PriceUtils.getPrice(goodsList.getGroupBuyingPrice()) + "");
        tv_price.setText(PriceUtils.getPrice(goodsList.getGoodsPrice()) + "元");

        tv_sold.setText("已售:" + groupBuyGoodDetailBean.getSold() + "");
        tv_GroupBuyingRemainingCount.setText(goodsList.getGroupBuyingRemainingCount() + "");
        tv_goods_count.setText(goodsList.getGroupBuyingCount() + "");


    }

    private void initSlider() {
        if (groupBuyGoodDetailBean.getGoodsPhotos() != null && !groupBuyGoodDetailBean.getGoodsPhotos().isEmpty()) {
            for (int i = 0; i < groupBuyGoodDetailBean.getGoodsPhotos().size(); i++) {
                urls.add(groupBuyGoodDetailBean.getGoodsPhotos().get(i).getUrl());
                TextSliderView textSliderView = new TextSliderView(this);
                textSliderView.description(goodsList.getGoodsName()).image(Api.getUrlIp() + groupBuyGoodDetailBean.getGoodsPhotos().get(i).getUrl()).showImageResForEmpty(R.drawable.pic_none).showImageResForError(R.drawable.pic_load_fail).setScaleType(BaseSliderView.ScaleType.CenterCrop).setOnSliderClickListener(this);
                if (textSliderView.getBundle() != null) {
                    textSliderView.getBundle().putInt("index", i);
                }
                slider.addSlider(textSliderView);
            }
            slider.setIndicatorPosition(InfiniteIndicatorLayout.IndicatorPosition.Center_Bottom);
            if (groupBuyGoodDetailBean.getGoodsPhotos().size() > 1) slider.startAutoScroll(10000);
            else {
                slider.setInfinite(false);
            }


        } else {
            DefaultSliderView defaultSliderView = new DefaultSliderView(this);
            defaultSliderView.image(R.drawable.img_default).setScaleType(BaseSliderView.ScaleType.CenterCrop);
            slider.addSlider(defaultSliderView);
            slider.setInfinite(false);
        }
    }


    private void setContentView() {
        setContentView(R.layout.activity_group_buy_details);
        slider = (InfiniteIndicatorLayout) findViewById(R.id.slider);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tv_group_buy_price = (TextView) findViewById(R.id.tv_group_buy_price);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        bt_go_buy = (TextView) findViewById(R.id.bt_go_buy);
        iv_IsDelivery = (ImageView) findViewById(R.id.iv_IsDelivery);
        tv_IsDelivery = (TextView) findViewById(R.id.tv_IsDelivery);
        tv_DeliveryInstructions = (TextView) findViewById(R.id.tv_DeliveryInstructions);
        tv_sold = (TextView) findViewById(R.id.tv_sold);
        tv_GroupBuyingRemainingCount = (TextView) findViewById(R.id.tv_GroupBuyingRemainingCount);
        tv_goods_count = (TextView) findViewById(R.id.tv_goods_count);
        groupbuy_time = (TextView) findViewById(R.id.groupbuy_time);
        tv_GoodsInstruction = (TextView) findViewById(R.id.tv_GoodsInstruction);
        tv_store = (TextView) findViewById(R.id.tv_store);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_business_hours = (TextView) findViewById(R.id.tv_business_hours);
        tv_tel = (Button) findViewById(R.id.tv_tel);
        tv_store_comments = (TextView) findViewById(R.id.tv_store_comments);
        listView = (com.saifan.wyy_ov.ui.view.NoScrollListView) findViewById(R.id.listView);
        listView.setFocusable(false);


    }


    @Override
    protected void onPause() {
        super.onPause();
        slider.stopAutoScroll();

    }


    // 立即购买
    public void goBuy(View v) {
        Intent intent = new Intent(this, SubmitOrderActivity.class);

        // 购买类型1为团购
        intent.putExtra("buy_type", 1);
        intent.putExtra("price", goodsList.getGroupBuyingPrice());
        intent.putExtra("storeId", groupBuyBean.getID());
        intent.putExtra("goodsName", goodsList.getGoodsName());
        intent.putExtra("goodsId", goodsList.getID());
        intent.putExtra("storeName", groupBuyBean.getStoreName());
        intent.putExtra("maxCount", goodsList.getGroupBuyingRemainingCount());
        intent.putExtra("photo", goodsList.getCoverPhoto());

        startActivity(intent);
    }



    // 店铺评价
    public void comments(View v) {
        Intent intent = new Intent(GroupBuyDetailsActivity.this, CommentsActivity.class);
        intent.putExtra("ID", Integer.valueOf(groupBuyBean.getID()));
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.group_buy_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_more) {
            listPopupWindow.setAnchorView(toolbar);
            listPopupWindow.setWidth(DensityUtil.getWidth(this) / 2);
            listPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            listPopupWindow.setHorizontalOffset(DensityUtil.getWidth(this) / 2);
            listPopupWindow.show();

        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSliderClick(BaseSliderView slider) {

        Intent intent = new Intent(GroupBuyDetailsActivity.this, ZoomImageActivity.class);
        int position = slider.getBundle().getInt("position");
        intent.putExtra("position", position);
        intent.putStringArrayListExtra("img", urls);
        startActivity(intent);

    }
    Button tel_button;
    public void call(View v) {

        tel_button = (Button) v;
        if (!StringUtil.isNullOrEmpty(tel_button.getText().toString())) {

            if (Build.VERSION.SDK_INT >= 23) {

                int checkCallPhonePermission = ContextCompat.checkSelfPermission( this, Manifest.permission.CALL_PHONE);
                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(GroupBuyDetailsActivity.this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
                    return;
                } else {
                    CallPhoneUtil.callPhone(GroupBuyDetailsActivity.this, tel_button.getText().toString());


                }
            } else {

                CallPhoneUtil.callPhone(GroupBuyDetailsActivity.this, tel_button.getText().toString());

            }


        }

    }



    private static final int CALL_PHONE = 123;
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                CallPhoneUtil.callPhone(GroupBuyDetailsActivity.this, tel_button.getText().toString());


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用拨打电话权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }
}
